package com.envy.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    //需要登录才能访问的页面

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断路径中是否包含login，如果包含则跳过，否则用户无法登录
        String path = request.getServletPath(); //获取到servlet之后的路径，不包括项目名的路径。如/staff/add.do
        if(path.toLowerCase().indexOf("login") !=-1){
            //说明url中存在login，需要跳过该url
            filterChain.doFilter(request,response);
        }else{
            //需要登录的链接
            HttpSession session = request.getSession();
            Object obj = session.getAttribute("USER");
            if(obj!=null){
                //说明用户登录了，所有链接跳过
                filterChain.doFilter(request,response);
            }else{
                //用户未登录，跳转到登录页面(注意此时用户是处于一级还是二级Url处)
                response.sendRedirect(request.getContextPath()+"/toLogin.do");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
